package com.yupi.springbootinit.mq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.apache.poi.ss.formula.functions.T;

/**
 * @Author: wenjupeng
 * @Date: 2025/02/16/0:00
 * @Description:
 * @Param:
 * @return:
 */


public class MultiConsumer {
    
    private static final String TASK_QUEUE_NAME = "multi_queue";
    
    public static void main(String[] argv) throws Exception {
        //建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        final Connection connection = factory.newConnection();
        for(int i = 0;i < 2;i++){
            final Channel channel = connection.createChannel();
            
            channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
            System.out.println(" [*] Raiting for messages. To exit press CTRL+C");
            
            channel.basicQos(1);
            //定义如何处理消息
            int finalI = i;
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                
                
                try {
                    //处理工作
                    System.out.println(" [x] Received '" + "编号:"+ finalI + ":" + message + "'");
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                    //停20秒 ，模拟机器处理能了有限
                    Thread.sleep(20000);
                    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(" [x] Done");
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                }
            };
            //开启消费监听
            channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> { });
            
        }
    }
    
    private static void doRork(String task) {
        for (char ch : task.toCharArray()) {
            if (ch == '.') {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException _ignored) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}